using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ToolsLayer;
using BusinessEntity;

namespace Webcar.BLL
{
    public class DeptManager
    {
        private DEPTEntity _Entity = new DEPTEntity();

        public DEPTEntity Entity
        {
            get { return _Entity; }
        }
        public DeptManager()
        {
        }

        public DeptManager(string id)
        {
            Entity.DEPT_CODE = id;
            if(!Entity.Retrieve())
                throw new WBException(WBErrorType.NotExistsError);
        }

        public void AddDept(string deptkind, string deptname)
        {
            this.Entity.IsPersistent = false;
            this.Entity.DEPT_CODE = GetNewCode();
            this.Entity.DEPT_KIND = deptkind;
            this.Entity.DEPT_NAME = deptname;
           
            this.Entity.Save();
        }

        public static string GetNewCode()
        {
            string sql = "select max(cast(dept_code as int)) from (select dept_code from dept) as a";
            string ret = DB.ExecuteScalar(sql);
            int r = Int32.Parse(ret) + 1;
            return r.ToString();
        }

        public int Delete()
        {
            if (!this.Entity.IsPersistent)
                return 0;
            string sql = "select count(1) from bs_car_record where dept_code='" + this.Entity.DEPT_CODE + "' and is_use<>'D'";
            string sql2 = "select count(1) from bs_emp where dept_code='" + this.Entity.DEPT_CODE + "' and is_use<>'D'";
            string ret = DB.ExecuteScalar(sql);
            if (ret != "0")
                throw new WBException(WBErrorType.DeleteCascadeError);
            ret = DB.ExecuteScalar(sql2);
            if (ret != "0")
                throw new WBException(WBErrorType.DeleteCascadeError);
            return this.Entity.Delete();
        }

    }
}
